﻿using System;
using System.Collections.Generic;

namespace TuxedoLib
{
	public static class Util
	{
		private static readonly Random random = new Random((int)(DateTime.Now.Ticks % Int32.MaxValue));

		public static int RandomInt(int minInclusive, int maxExclusive)
		{
			return random.Next(minInclusive, maxExclusive);
		}

		public static bool RandomBool()
		{
			return random.Next(2) == 1;
		}

		public static double RandomDouble()
		{
			return random.NextDouble();
		}

		public static void ShuffleList<T>(IList<T> items)
		{
			int length = items.Count;
			T swap;
			int swapIndex;
			for (int i = length - 1; i >= 0; --i)
			{
				swap = items[i];
				swapIndex = random.Next(0, length);
				items[i] = items[swapIndex];
				items[swapIndex] = swap;
			}
		}

		/// <summary>
		/// Returns an array that is the old list repeated multiplier times.
		/// </summary>
		public static T[] MultiplyList<T>(IList<T> list, int multiplier)
		{
			T[] output = new T[multiplier * list.Count];
			int countDown = multiplier;
			int listSize = list.Count;
			int i;
			while (countDown > 0)
			{
				--countDown;
				for (i = listSize - 1; i >= 0; --i)
				{
					output[i + listSize * countDown] = list[i];
				}
			}
			return output;
		}

		public static V DictionaryGet<K, V>(IDictionary<K, V> dict, K key)
		{
			V output;
			if (dict.TryGetValue(key, out output))
			{
				return output;
			}
			return default(V);
		}

		public static T[] ArraySlice<T>(IList<T> list, int start, int end)
		{
			if (end <= 0)
			{
				end += list.Count;
			}

			T[] output = new T[end - start];
			for (int i = 0; i < output.Length; ++i)
			{
				output[i] = list[start + i];
			}

			return output;
		}

		public static T[] ArrayConcat<T>(IList<T> listA, IList<T> listB)
		{
			T[] output = new T[listA.Count + listB.Count];
			int index = 0;
			int length = listA.Count;
			for (int i = 0; i < length; ++i)
			{
				output[index++] = listA[i];
			}
			length = listB.Count;
			for (int i = 0; i < length; ++i)
			{
				output[index++] = listB[i];
			}
			return output;
		}
	}
}
